package com.tanhua.dubbo.api.mongo;

import com.mongodb.client.result.UpdateResult;
import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.mongo.Publish;
import com.tanhua.domain.vo.PageResult;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.List;


@Service
public class CommentApiImpl implements CommentApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 动态点赞
     * 动态喜欢
     *
     * @param comment
     * @return
     */
    @Override
    public long save(Comment comment) {
        //补全动态作者id
        Publish publish = mongoTemplate.findById(comment.getTargetId(), Publish.class);
        Long publishUserId = publish.getUserId();//动态作者id
        //添加评论表记录
        comment.setTargetUserId(publishUserId); //这条动态作者
        comment.setCreated(System.currentTimeMillis()); //当前时间
        //加入数据库
        mongoTemplate.insert(comment);
        //更新动态的点赞数
        Query publishQuery = new Query(Criteria.where("_id").is(comment.getTargetId()));
        //更新的操作，自增1
        Update update = new Update();
        update.inc(comment.getCol(), 1);
        mongoTemplate.updateFirst(publishQuery, update, Publish.class);
        //查询最新的点赞数
        publish = mongoTemplate.findById(comment.getTargetId(), Publish.class);
        Integer count = publish.getLikeCount(); //默认返回点赞数
        // commentType=3代表喜欢
        if (3 == comment.getCommentType()) {
            count = publish.getLoveCount();
        }
        return count;
    }

    /**
     * 动态取消点赞
     * 动态取消喜欢
     *
     * @param comment
     * @return
     */
    @Override
    public long remove(Comment comment) {
        //1.先删除评论表数据
        //1.2构建删除条件
        Query CommentQuery = new Query(Criteria.where("targetId").is(comment.getTargetId()).and("commentType").is(comment.getCommentType()));

        //1.3删除
        mongoTemplate.remove(CommentQuery, Comment.class);

        //2.更新动态点赞数-1
        //构建更新条件
        Query publishQuery = new Query(Criteria.where("_id").is(comment.getTargetId()));
        Update update = new Update();
        update.inc(comment.getCol(), -1);

        mongoTemplate.updateFirst(publishQuery, update, Publish.class);
        //查询最新的点赞数
        Publish publish = mongoTemplate.findById(comment.getTargetId(), Publish.class);
        Integer count = publish.getLikeCount();
        if (3 == comment.getCommentType()) {
            count = publish.getLoveCount();
        }
        return count;
    }

    /**
     * 通过动态id，分页查询评论列表
     *
     * @param publishId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageResult findPage(String publishId, Long page, Long pageSize) {
        Query query = new Query(Criteria.where("targetId").is(new ObjectId(publishId)).and("commentType").is(2)); //代表评论

        // 统计总数
        long count = mongoTemplate.count(query, Comment.class);

        List<Comment> commentList = new ArrayList<>();
        // 总数>0
        if (count > 0) {
            // 按时间降序
            query.with(Sort.by(Sort.Order.desc("created")));
            // 设置分页
            query.skip((page - 1) * pageSize).limit(pageSize.intValue());

            commentList = mongoTemplate.find(query, Comment.class);
        }

        // 构建PageResult返回
        return PageResult.pageResult(page, pageSize, commentList, count);


    }

    /**
     * 评论点赞
     *
     * @param comment
     * @return
     */
    @Override
    public long likeComment(Comment comment) {
        //补全评论作者id
        Comment TargetComment = mongoTemplate.findById(comment.getTargetId(), Comment.class);
        Long userId = TargetComment.getUserId(); //原评论作者id

        //添加评论表记录
        comment.setTargetUserId(userId); //目标作者id
        comment.setCreated(System.currentTimeMillis()); //当前时间

        //加入数据库
        mongoTemplate.insert(comment);

        //更新评论点赞数
        Query commentQuery = new Query(Criteria.where("_id").is(comment.getTargetId()));

        Update update = new Update();
        update.inc("likeCount", 1);
        //更新
        mongoTemplate.updateFirst(commentQuery, update, Comment.class);

        //重新查询最新的点赞数
        Comment templateById = mongoTemplate.findById(comment.getTargetId(), Comment.class);
        return templateById.getLikeCount();


    }

    /**
     * 评论取消点赞
     *
     * @param comment
     * @return
     */
    @Override
    public long dislikeComment(Comment comment) {

        //1. 删除评论表数据
        // 构建删除的条件：3个
        Query commentQuery = new Query(Criteria.where("targetId").is(comment.getTargetId())
                .and("commentType").is(comment.getCommentType())
                .and("userId").is(comment.getUserId()));

        mongoTemplate.remove(commentQuery, Comment.class);
        //更新原来的评论的点赞数 -1
        //构建条件
        commentQuery = new Query(Criteria.where("_id").is(comment.getTargetId()));

        // 创建更新自减1
        Update update = new Update();
        update.inc("likeCount", -1);

        //更新
        mongoTemplate.updateFirst(commentQuery, update, Comment.class);

        //查询最新的数据
        Comment commentTarget = mongoTemplate.findById(comment.getTargetId(), Comment.class);

        return commentTarget.getLikeCount();
    }

    /**
     * 谁对登录用户点赞通知
     *
     * @param commentType 1:点赞，2：评论，3：喜欢
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public PageResult findPageByUserId(Long loginUserId, int commentType, Long page, Long pagesize) {

        //构建条件
        Query query = new Query(Criteria.where("commentType").is(commentType).and("targetUserId").is(loginUserId));

        //查询总数
        long count = mongoTemplate.count(query, Comment.class);
        List<Comment> commentList = new ArrayList<>();
        if (count > 0) {
            //构建分页
            query.skip((page - 1) * pagesize).limit(pagesize.intValue());
            // 排序
            query.with(Sort.by(Sort.Order.desc("created")));
            //查询
            commentList = mongoTemplate.find(query, Comment.class);

        }
        //返回
        return PageResult.pageResult(page, pagesize, commentList, count);
    }
}
